import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;


/**
 * 快速入门
 *
 * @author xgc
 * @date 2023/12/07
 */
@Slf4j
public class QuickStart {
    public static void main(String[] args) {
        //根据ini配置文件，获取一些基本信息（用户、密码、角色、权限）
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //获取一个SecurityManager对象
        SecurityManager instance = factory.getInstance();
        //获取当前主体（用户）
        SecurityUtils.setSecurityManager(instance);
        Subject subject = SecurityUtils.getSubject();
        //获取当前会话
        Session session = subject.getSession();
        session.setAttribute("someKey","aValue");
        //判断是否登录
        if (!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr","vespa");
            token.setRememberMe(true);
            try {
                subject.login(token);
            } catch (UnknownAccountException uae) {
                log.error("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.error("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.error("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
        }
        //打印其标识主体(在本例中为用户名):
        log.info( "User [" + subject.getPrincipal() + "] logged in successfully." );
        //查看用户是否为对应角色
        if ( subject.hasRole( "schwartz" ) ) {
            log.info("May the Schwartz be with you!" );
        } else {
            log.info( "Hello, mere mortal." );
        }
        //查看用户是否有对应权限
        if (subject.isPermitted("lightsaber:*")){
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }
        if ( subject.isPermitted( "winnebago:drive:eagle5" ) ) {
            log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }
        //登出系统
        subject.logout(); //removes all identifying information and invalidates their session too.

    }
}
